package sdu.attendancechecker.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sdu.attendancechecker.dto.Admin;
import sdu.attendancechecker.dto.Question;
import sdu.attendancechecker.services.AdminService;

/**
 * Servlet implementation class AdminSupportServlet
 */

public class AdminSupportServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public AdminSupportServlet() {
		super();

	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (request.getSession().getAttribute("admin") == null) {
			RequestDispatcher dispatcher = request
					.getRequestDispatcher("admin/login");
			dispatcher.forward(request, response);
			return;
		}

		String destination = "admin/questions.jsp";

		if (request.getParameter("command") != null) {
			if (request.getParameter("command").equals("answer")) {
				destination = "admin/answer.jsp";
				int question_id = Integer.parseInt(request.getParameter("id"));
				request.getSession().setAttribute("question_id", question_id);

				Question q = AdminService.getQuestionById(question_id);
				request.setAttribute("question", q);
			}

		}
		ArrayList<Question> questions = AdminService.getQuestions();
		request.setAttribute("questions", questions);
		RequestDispatcher dispatcher = request
				.getRequestDispatcher(destination);
		dispatcher.forward(request, response);

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (request.getSession().getAttribute("admin") == null) {
			RequestDispatcher dispatcher = request
					.getRequestDispatcher("admin/login");
			dispatcher.forward(request, response);
			return;
		}

		if (request.getParameter("command") != null) {
			String command = request.getParameter("command");
			response.setContentType("text/html;charset=UTF-8");
			if (command.equals("delete")) {
				Integer id = Integer.parseInt(request.getParameter("id"));
				boolean success = AdminService.deleteQuestionById(id);
				response.getWriter().println(success ? 1 : 0);
			}
		}

		if (request.getParameter("answertext") != null) {
			if (request.getSession().getAttribute("question_id") != null) {
				String answer = request.getParameter("answertext");
				int question_id = (Integer) request.getSession().getAttribute(
						"question_id");
				request.getSession().removeAttribute("question_id");

				AdminService.answerQuestion(question_id, answer.trim());
			}
			response.sendRedirect("admin_support");
		}

	}

}
